// pages/pay/pay.js
import store from '../../modules/store'
import tool from '../../modules/tool'
import wsh from '../../modules/webSocketHandler'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupons: [],
    show: false,
    items: undefined,
    priceTotalDisplay: 0,
    discountTotalDisplay: 0,
    vipStatus: {},
    incom: undefined,
    succ: false,
    code: '',
    address: '',
    addressIndex: 0,
    payWayIndex: 0,
    phone: '',
    text: '',
    havePro: false,
    orderStatus: {},
    orderNo: '',
    controlButton: [],
    takeAddress: ''
  },

  handleShowCode() {
    tool.handleShowModel(this.data.orderStatus.code, false)
  },

  handleShowDetailPage(e) {
    tool.handleShowProductActivityDetailPage(e.currentTarget.dataset.ispro, e.currentTarget.dataset.id)
  },

  async handleGetOrderStatusData(orderNo, sec = false) {
    let re = await tool.requestData('/order/getStatus', {
      orderNo
    }, 'get')
    if (re.status) {
      // console.log(JSON.stringify(re.data))
      this.setData({
        orderStatus: re.data,
        succ: true,
        show: true,
        orderNo,
        orderInfo: [
          {
            title: '订单号',
            right: {
              type: 'text',
              value: re.data.orderNo
            },
            disabled: true
          },
          {
            title: '支付金额',
            right: {
              type: 'text',
              value: `￥${re.data.totalPrice_read}`
            },
            disabled: true
          },
          {
            title: '支付时间',
            right: {
              type: 'text',
              value: re.data.paidAt_read
            },
            disabled: true
          },
          {
            title: '地址',
            right: {
              type: 'text',
              value: re.data.address
            },
            disabled: true
          },
          {
            title: '预留电话',
            right: {
              type: 'text',
              value: re.data.phone
            },
            callBack: async () => {
              wx.makePhoneCall({
                phoneNumber: re.data.phone,
              })
            }
          },
          {
            title: '备注',
            right: {
              type: 'text',
              value: re.data.text
            },
            callBack: async () => {
              tool.handleShowModel(re.data.text, false)
            }
          },
        ],
        controlButton: [
          {
            title: '联系商家',
            icon: '联系电话',
            callBack: async () => {
              let re = await tool.requestData('/setting/get', {
                key: 'phone'
              }, 'get')
              if (re.status) {
                if (re.data == undefined) {
                  tool.handleShowToast('无可用电话')
                } else {
                  wx.makePhoneCall({
                    phoneNumber: `${re.data}`,
                  })
                }
              } else {
                tool.handleShowToast(re.content, 'error')
              }
            }
          },
          ...await tool.execFunc(async () => {
            if (!this.data.isAdmin) return []
            if (re.data.type == 1) return []
            if (re.data.status == 0) return []
            return [
              {
                title: '修改状态',
                icon: 'changeStatus',
                callBack: async () => {
                  const change = async (code) => {
                    let re1 = await tool.requestData('/order/updateStatus', {
                      orderNo: re.data.orderNo,
                      status: code
                    })
                    if (re1.status) {
                      this.handleGetOrderStatusData(re.data.orderNo)
                    } else {
                      tool.handleShowToast(re1.content, 'error')
                    }
                  }
                  let ls = [
                    {
                      title: '正在备餐',
                      code: 1
                    }
                  ]
                  if (re.data.type == 2) {
                    ls.push({
                      title: '等待取餐',
                      code: 3
                    })
                  } else {
                    ls.push({
                      title: '正在配送',
                      code: 2
                    })
                  }
                  ls.push({
                    title: '已完成',
                    code: 4
                  })
                  wx.showActionSheet({
                    itemList: (() => {
                      let tt = []
                      for (let i = 0; i < ls.length; i++) {
                        tt.push(ls[i].title)
                      }
                      return tt
                    })(),
                    success: (e) => {
                      e = e.tapIndex
                      change(ls[e].code)
                    }
                  })
                }
              }
            ]
          }),
          ...await tool.execFunc(async () => {
            if (!this.data.isAdmin) return
            return [
              {
                title: '打印标签',
                icon: 'printer',
                callBack: async () => {
                  tool.printLabel(this.data.orderNo, true)
                }
              }
            ]
          }),
          ...await tool.execFunc(async () => {
            if (!this.data.isAdmin) return
            return [
              {
                title: '删除订单',
                icon: 'delete',
                callBack: async () => {
                  let re = await tool.requestData('/pay/refund', {
                    orderNo: this.data.orderStatus.orderNo,
                    refundAmount: this.data.orderStatus.totalPrice
                  })
                  if (re.status) {
                    tool.handleShowToast('成功')
                    await tool.wait(0.5)
                    wx.navigateBack()
                  } else {
                    tool.handleShowToast(re.content, 'error')
                  }
                }
              }
            ]
          }),
        ]
      })
      wx.setNavigationBarTitle({
        title: '订单详情',
      })
    } else {
      tool.handleShowToast(re.content, 'error')
      await tool.wait(1)
      if (this.data.incom == undefined) {
        wx.navigateBack()
      } else {
        if (sec == false) {
          this.handleGetOrderStatusData(orderNo, true)
        }
      }
    }
  },

  handleChangePayWay(e) {
    wx.showActionSheet({
      itemList: ['微信支付', '余额支付'],
      success: (e) => {
        e = e.tapIndex
        if (e === 0) {
          if (this.data.priceTotalDisplay == '0' && !e) {
            tool.handleShowToast('仅在价格大于0时可选')
            return
          }
          this.setData({
            payWayIndex: 0
          })
        }
        if (e === 1) {
          this.setData({
            payWayIndex: 1
          })

        }
      }
    })
  },

  handleChangeAddressSelected(e) {
    e = e.currentTarget.dataset.index
    if (e == 0) {
      this.setData({
        address: '堂食',
        addressIndex: 0
      })
    }
    if (e == 1) {
      if (!store.getItem('userData').address || store.getItem('userData').address.length < 6) {
        tool.handleShowModel('收货地址长度过短，是否现在修改？', true, () => {
          tool.handleSetAddress()
        })
        return
      }
      this.setData({
        address: store.getItem('userData').address,
        addressIndex: 1
      })
    }
    if (e == 2) {
      this.setData({
        address: '自取',
        addressIndex: 2
      })
    }
  },

  handleBack() {
    wx.navigateBack()
  },

  async handleServerStartPay(address) {
    let re = await tool.requestData('/pay/start', {
      items: this.data.items ? this.data.items : this.data.incom,
      openId: store.getItem('userData').openId,
      address,
      payWay: this.data.payWayIndex,
      phone: this.data.phone,
      text: this.data.text
    })
    if (re.status) {
      store.setItem('updateCartPage')
      store.setItem('indexHidePayBoard')
      store.setItem('detailPageHidePayBoard')
      this.handleGetOrderStatusData(re.data.orderNo)
      tool.handleUpdateCartNum()
      if (this.data.payWayIndex == 0) {
        tool.pay(0, `微信支付${re.data.orderNo}`, re.data.orderNo)
      }
    } else {
      tool.handleShowToast(re.content, 'error')
    }
  },

  async startPay() {
    await this.updateDisplay()
    let havePro = false
    for (let i = 0; i < this.data.items.length; i++)if (this.data.items[i].isPro) havePro = true
    if (havePro) {
      if (this.data.payWayIndex == 0) {
        this.handleServerStartPay(this.data.address)
      } else {
        tool.handleShowModel(`是否立即支付￥${this.data.priceTotalDisplay}？`, true, async () => {
          this.handleServerStartPay(this.data.address)
        })
      }
      return
      // wx.showActionSheet({
      //   itemList: ['堂食', '配送'],
      //   alertText: '请选择',
      //   success: (e) => {
      //     e = e.tapIndex
      //     if (e) {
      //       if (!store.getItem('userData').address || store.getItem('userData').address.length < 10) {
      //         tool.handleShowModel('收货地址长度不能少于10，请前往个人中心修改。')
      //         return
      //       }
      //       tool.handleShowModel(`是否立即支付￥${this.data.priceTotalDisplay}，并将商品配送至${store.getItem('userData').address}？`, true, async () => {

      //       })
      //     } else {
      //       tool.handleShowModel(`是否立即支付￥${this.data.priceTotalDisplay}，并在店内用餐？`, true, async () => {
      //         this.handleServerStartPay('堂食')
      //       })
      //     }
      //   }
      // })
    } else {
      tool.handleShowModel(`是否立即支付￥${this.data.priceTotalDisplay}？`, true, async () => {
        this.handleServerStartPay('无商品')
      })
    }
  },

  async handleUnuseDiscount(e) {
    e = e.currentTarget.dataset.index
    let index = e
    await this.updateDisplay({
      index,
    })
  },

  async handleUseDiscount(e) {
    e = e.currentTarget.dataset.index
    let index = e
    wx.showActionSheet({
      itemList: ['使用优惠券', '使用PLUS会员'],
      success: async (e) => {
        e = e.tapIndex
        if (e) {
          if (!this.data.isVIP) {
            tool.handleShowToast('您现在不是PLUS会员', 'error')
          } else {
            await this.updateDisplay({
              index,
              setVip: this.data.items[index].isPro
            })
          }
        } else {
          if (!this.data.coupons.length) {
            tool.handleShowToast('没有优惠券')
            return
          }
          tool.handleShowSelectCouponPage(async (selected, done) => {
            done()
            await this.updateDisplay({
              index: index,
              setCoupon: selected.discount
            })
          })
        }
      }
    })
  },

  async updateDisplay(set = undefined, auto = false) {
    let re = await tool.requestData('/pay/getPrice', {
      items: this.data.items ? this.data.items : this.data.incom,
      openId: store.getItem('userData').openId,
      set,
      auto
    })
    if (re.status) {
      this.setData({
        coupons: re.data.coupons,
        items: re.data.items,
        vipStatus: re.data.vipStatus,
        priceTotalDisplay: re.data.priceTotalDisplay,
        discountTotalDisplay: re.data.discountTotalDisplay,
      })
      if (re.data.priceTotal == 0) {
        this.setData({
          payWayIndex: 1
        })
      }
    } else {
      wx.navigateBack()
      tool.handleShowToast(re.content, 'error')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    tool.setPageData(this)
    if (store.getItem('orderDetailPage') != undefined) {
      wx.setNavigationBarTitle({
        title: '订单详情',
      })
      this.handleGetOrderStatusData(store.getItem('orderDetailPage'))
      store.removeItem('orderDetailPage')
      return
    }
    if (store.getItem('payPage') == undefined) {
      wx.navigateBack()
      return
    }
    let t = store.getItem('payPage')
    let re = []
    for (let i = 0; i < t.length; i++) {
      if (t[i].isPro) {
        this.setData({
          havePro: true,
          address: '无'
        })
      }
      for (let i1 = 0; i1 < t[i].num; i1++) {
        let c = JSON.parse(JSON.stringify(t[i]))
        c.num = 1
        c.numOld = t[i].num
        c.index = i1
        c.indexMax = t[i].num - 1
        re.push(c)
      }
    }
    this.setData({
      incom: re,
      address: '堂食'
    })
    store.removeItem('payPage')
    await this.updateDisplay(undefined, true)
    {
      let re = await tool.requestData('/setting/get', {
        key: 'takeAddress'
      }, 'get')
      if (re.status) {
        this.setData({
          takeAddress: re.data
        })
      } else {

      }
    }
    this.setData({
      show: true,
      balance_read: store.getItem('userData').balance_read,
      phone: `${store.getItem('userData').phone}`
    })
    store.onChange('userData', () => {
      if (this.data.addressIndex != 1) return
      this.setData({
        address: store.getItem('userData').address
      })
    })

    tool.webSocket.onMessage('orderStatusChanged', (e) => {
      if (e.orderNo == this.data.orderNo) {
        this.handleGetOrderStatusData(e.orderNo)
        wx.vibrateLong()
      }
    })
  },

  handleInputPhone() {
    tool.controlInput('预留电话', '', 'singleText', this.data.phone, (value, done) => {
      this.setData({
        phone: value
      })
      done()
    }, (value) => {
      let t = /(1[0-9]{10}|\+[0-9]{1,3}1[0-9]{10})/
      if (t.test(value) == false) throw '请输入正确的手机号'
    })
  },

  handleInputText() {
    tool.controlInput('订单备注', '', 'multipleText', this.data.text, (value, done) => {
      this.setData({
        text: value
      })
      done()
    }, (value) => {
      if (value.length > 128) {
        throw '长度不能超过128'
      }
    })
  },

  handleEditAddress() {
    tool.handleSetAddress()
  },

  handleShowUserInfoPage() {
    tool.handleShowUserInfoPage(this.data.orderStatus.userInfo.openId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    if (this.data.succ) {
      await this.handleGetOrderStatusData(this.data.orderNo)
    } else {
      await this.updateDisplay(undefined, false)
    }
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})